extends Container

@export var level = 0
@export var Cardname = ""
@export var Value = 0

var select = false
var canselect = false
var dragging = false
var justdrag = false
var justInsert = false
var pos = 0
var candrag = true
var in_box = false
var in_other_box = null

var testt = 0;


func __get_in_box_pos(box,n_pos:int) -> Vector2:
	return Vector2(box.gwide+(n_pos*(self.size.x + box.gwide)),box.ghigh)
	
func __put_in_box(box,n_pos:int):
	position = __get_in_box_pos(box,n_pos)
	
func __cancel_dragging(p_pos):
	if select:
		position = p_pos
		in_other_box = null

func __add_in_box(box,n_pos:int):
	position = __get_in_box_pos(box,n_pos) + Vector2(0,-128*scale.y)
	__Play_pos_now_Animation(self,$AnimationPlayer,"down")

func __change_pos(box,p_pos:int,n_pos:int):
	if not select:
		position = __get_in_box_pos(box,p_pos)
		__Play_pos_now_Animation(self,$AnimationPlayer,"up")
	var CA:Animation = $AnimationPlayer.get_animation("change_pos_in_box")
	CA.track_set_key_value(0,0,__get_in_box_pos(box,p_pos) + (Vector2(0,-128*scale.y)))
	var posnv = __get_in_box_pos(box,n_pos) + (Vector2(0,-128*scale.y))
	CA.track_set_key_value(0,1,posnv)
	$AnimationPlayer.play("change_pos_in_box")
	position = posnv
	__Play_pos_now_Animation(self,$AnimationPlayer,"down")
	pass

static func __Play_pos_now_Animation(node,player:AnimationPlayer,name:String):
	var now_pos = node.position
	var PA:Animation = player.get_animation(name)
	if PA == null:
		print("no Animation named "+name)
		return
	if(name == "up"):
		PA.track_set_key_value(0,0,now_pos)
		PA.track_set_key_value(0,1,now_pos+Vector2(0,-128* node.scale.y))
	if(name == "down"):
		PA.track_set_key_value(0,0,now_pos)
		PA.track_set_key_value(0,1,now_pos+Vector2(0,128 * node.scale.y))
	player.play(name)
	
func _ready() -> void:
	tooltip_text = Cardname + "牌"
	# set_mouse_filter(1)
	pass

func _process(delta: float) -> void:
	
	$Label.text = str(int(1.0/delta))

func _gui_input(event: InputEvent) -> void:
	if select:
		if __BaseFunc.__dragging_(event,self):
			pass
	else :
		if __BaseFunc.__should_dragging_(event,self):
			pass
			
	
	if not candrag:
		if in_box and justdrag and event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.is_released():
			tooltip_text = "in:" + str(in_box) + "\n" +"ino:"+str(in_other_box) + "\n"+"par:"+str(get_parent())
			if in_other_box == null:
				var p_pos = __get_in_box_pos(get_parent(),pos)
				__cancel_dragging(p_pos+Vector2(0,-128*scale.y))
			elif in_other_box != null:
				if select:
					if in_box:
						get_parent().call("__Card_change_box",in_other_box,self)
						__cancel_dragging(__get_in_box_pos(get_parent(),pos)+Vector2(0,-128*scale.y))
					else:
						in_other_box.__Add_Card_node(self)
	__BaseFunc.__By_select(event,self,Callable(__Play_pos_now_Animation))

func __delete_Crad():
	queue_free()
